package com.liuyc.lib.image.loader.utils.imp

import com.bumptech.glide.disklrucache.DiskLruCache
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.cache.DiskCache
import com.bumptech.glide.load.engine.cache.SafeKeyGenerator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.signature.EmptySignature
import com.liuyc.lib.common.AppGlobals
import com.liuyc.lib.image.loader.BuildConfig
import com.liuyc.lib.image.loader.utils.IImageLoaderCache
import java.io.File
import java.security.MessageDigest


/**
 * ImageLoaderCacheImp
 * 图片 缓存 类
 * 刘隽
 */
class ImageLoaderCacheImp : IImageLoaderCache {

    class OriginalKey(private val id: Key, private val signature: Key) : Key {

        override fun equals(other: Any?): Boolean {
            var equals = false
            if (other is OriginalKey) {
                equals = id.equals(other.id) && signature.equals(other.signature)
            }

            var tr = "2"

            return equals
        }

        override fun hashCode(): Int {
            var result: Int = id.hashCode()
            result = 31 * result + signature.hashCode()
            return result
        }

        override fun updateDiskCacheKey(messageDigest: MessageDigest) {
            id.updateDiskCacheKey(messageDigest);
            signature.updateDiskCacheKey(messageDigest);
        }
    }

    /**
     * 根据 URL  获取缓存图片位置
     */
    override fun getCacheFile(url: String): File? {

        var safeKeyGenerator = SafeKeyGenerator()

        var safeKey = safeKeyGenerator.getSafeKey(OriginalKey(GlideUrl(url), EmptySignature.obtain()))


        try {
            val cacheSize: Long = 100 * 1000 * 1000

            var file = File(AppGlobals.get()?.getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR)

            val diskLruCache: DiskLruCache = DiskLruCache.open(file, 1, 1, cacheSize)

            val value: DiskLruCache.Value = diskLruCache.get(safeKey)
            if (value != null) {
                if (BuildConfig.DEBUG) {
                    //                UCSLogUtils.d("图片本地位置=" + value.getFile(0))
                }
                return value.getFile(0)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }
}